/**
 * 路由配置
 * 
 * 功能说明：
 * - 配置应用的路由规则
 * - 管理页面之间的导航
 */

import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '@/utils/auth'
import ChatPage from '../views/ChatPage.vue'
import MapPage from '../views/MapPage.vue'
import LoginPage from '../views/LoginPage.vue'
import KnowledgeBasePage from '../views/KnowledgeBase.vue'
import DevelopmentPlanPage from '../views/DevelopmentPlan.vue'
import AgentConfigPage from '../views/AgentConfig.vue'
import ModelConfigPage from '../views/ModelConfig.vue'
import ToolConfigPage from '../views/ToolConfig.vue'

// 定义路由规则
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: LoginPage,
    meta: {
      title: '登录',
      requiresAuth: false
    },
  },
  {
    path: '/',
    name: 'Chat',
    component: ChatPage,
    meta: {
      title: '聊天',
      requiresAuth: true
    },
  },
  {
    path: '/map',
    name: 'Map',
    component: MapPage,
    meta: {
      title: '地图',
      requiresAuth: true
    },
  },
  {
    path: '/knowledge-base',
    name: 'KnowledgeBase',
    component: KnowledgeBasePage,
    meta: {
      title: '知识库',
      requiresAuth: true
    },
  },
  {
    path: '/development-plan',
    name: 'DevelopmentPlan',
    component: DevelopmentPlanPage,
    meta: {
      title: '开发计划',
      requiresAuth: true
    },
  },
  {
    path: '/agent-config',
    name: 'AgentConfig',
    component: AgentConfigPage,
    meta: {
      title: 'Agent配置',
      requiresAuth: true
    },
  },
  {
    path: '/model-config',
    name: 'ModelConfig',
    component: ModelConfigPage,
    meta: {
      title: '模型配置',
      requiresAuth: true
    },
  },
  {
    path: '/tool-config',
    name: 'ToolConfig',
    component: ToolConfigPage,
    meta: {
      title: '工具管理',
      requiresAuth: true
    },
  },
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由守卫：设置页面标题和登录验证
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - Agent Chat`
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const token = getToken()
    if (!token) {
      // 未登录，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    // 如果已登录，访问登录页时跳转到首页
    if (to.path === '/login') {
      const token = getToken()
      if (token) {
        next('/')
      } else {
        next()
      }
    } else {
      next()
    }
  }
})

export default router

